package com.zsj.filter;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Description:
 * @Author:
 * @Date:
 */
@Slf4j
@Component
@Order(1)
public class OrderNoFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        try {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            String requestURI = httpServletRequest.getRequestURI();
            String requestMethod = httpServletRequest.getMethod();
            // 过滤掉/请求，但发放行健康检查
            if ("/".equals(requestURI) && !"HEAD".equalsIgnoreCase(requestMethod)) {
                return;
            }

            // 健康检查
            if ("HEAD".equalsIgnoreCase(httpServletRequest.getMethod())) {
                filterChain.doFilter(request, response);
            } else {
                log.info("为日志赋值dy订单号");
                if (null != httpServletRequest.getContentType() && httpServletRequest.getContentType().startsWith(
                        "application/json")) {
                    ParameterRequestWrapper requestWrapper = new ParameterRequestWrapper(httpServletRequest);
                    String body = new String(requestWrapper.getBody());
                    JSONObject parameters = JSONObject.parseObject(body);
                    MDC.put("dyOrderNo", parameters.getString("ChargeNo"));
                    filterChain.doFilter(requestWrapper, response);
                } else {
                    log.info("contentType:{}", httpServletRequest.getContentType());
                    //throw new BusinessException(ErrorCodeEnum.PARAM_ERROR);
                    filterChain.doFilter(request, response);
                }
            }
        } catch (Exception e) {
            log.error("为日志赋值dy订单号异常", e);
            filterChain.doFilter(request, response);
            //throw new BusinessException(ErrorCodeEnum.SUPPLIER_FAIL);
        }
    }
}
